
"""此种对象通过定义-aenter_()和aexit_)方法来对 async_with 语句中的环境进行控制。由 PEP 492引入。"""

import asyncio


class AsyncContextManager:

    async def do_something(self):
        # 假设异步操作数据库
        return 666

    async def __aenter__(self):
        # 假设异步连接数据库
        # self.conn = await self.do_something()
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        # 假设异步关闭数据库
        await asyncio.sleep(1)


async def main():
    async with AsyncContextManager() as conn:
        result = await conn.do_something()
        print(result)


asyncio.run(main())
